package com.mud.mudcommune.view.activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.mud.mudcommune.R;
import com.mud.mudcommune.entry.RegisterEntry;
import com.mud.mudcommune.entry.VerifyEntry;
import com.mud.mudcommune.http.NetUtils;
import com.mud.mudcommune.utils.LogUtils;
import com.mud.mudcommune.http.ApiService;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RegisterActivity extends Activity implements Callback<RegisterEntry> {
    private static final String TAG = RegisterActivity.class.getSimpleName();
    @BindView(R.id.head_title)
    TextView title;
    @BindView(R.id.get_code)
    TextView getCode; // 获取验证码
    @BindView(R.id.register_tel)
    EditText telEdit;
    @BindView(R.id.security_code)
    EditText securityCodeEdit;
    @BindView(R.id.register_password)
    EditText passwordEdit;
    @BindView(R.id.resume_password)
    EditText resumepasswordEdit;
    @BindView(R.id.register_city)
    EditText cityEdit;
    @BindView(R.id.Register_case_back)
    ImageView Registerback;
    @BindView(R.id.commit_Register)
    Button commit_button;
    @BindView(R.id.Register_progressBar)
    ProgressBar mProgressBar;
    boolean onClickCode = true;
    // private String securityCode, password, city;
    private static final int CODE_ING = 1; // 已发送，倒计时
    private static final int CODE_REPEAT = 2;//重新发送
    private static int tempSecond = 45;
    private Unbinder unbinder;
    private String mobileCode, tel;
    private static int code = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_register);
        unbinder = ButterKnife.bind(this);
        title.setText("注册");
    }


    @OnClick({R.id.Register_case_back, R.id.get_code, R.id.commit_Register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_code: {
                tel = telEdit.getText().toString();
                mobileCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
                if (tel == null || "".equals(tel)) {
                    Toast.makeText(this, "手机号码不能为空", Toast.LENGTH_SHORT).show();
                    break;
                } else if (tel.length() != 11) {
                    Toast.makeText(this, "请输入正确的手机号位数", Toast.LENGTH_SHORT).show();
                    break;
                } else {
                    //new GetCodeThread().start(); //
                    onClickCode = false; // 验证码已发送
                    mobileCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
                    //向用户发送验证码
                    String content = new String("您的验证码是：" + mobileCode + "。请不要把验证码泄露给其他人。");
                    NetUtils.createService(ApiService.class, ApiService.SMS_BASE_URL).
                            getSms("Submit", "cf_nbgs", "f1c148cc788c8e1fe24983e3dc9d2775", tel, content, "json").
                            enqueue(new Callback<VerifyEntry>() {
                                @Override
                                public void onResponse(Call<VerifyEntry> call, Response<VerifyEntry> response) {
                                    VerifyEntry verifyEntry = response.body();
                                    LogUtils.i(TAG, response.body().toString());
                                    if (verifyEntry.getCode() == 2) { // 短信发送成功
                                        LogUtils.i("SendSms:", "SMS_SEND_SUCCESS " + ApiService.SMS_SEND_SUCCESS);
                                        code = ApiService.SMS_SEND_SUCCESS;
                                    } else if (verifyEntry.getCode() == 403 || verifyEntry.getCode() == 406 || verifyEntry.getCode() == 4030) { // 手机号有误
                                        code = ApiService.PHONE_NUM_WRONG; // 手机号码有误
                                    } else {
                                        code = ApiService.SMS_SEND_FAILURE; // 其它原因导致收不到验证码
                                    }
                                    LogUtils.i(TAG, response.body().toString());
                                }

                                @Override
                                public void onFailure(Call<VerifyEntry> call, Throwable t) {
                                    t.printStackTrace();
                                }
                            });

//                    Server server = RetrofitManager.getInstance().getRetrofit().create(Server.class);
//                    Call<String> call = server.getSms("Submit", "cf_nbgs", "f1c148cc788c8e1fe24983e3dc9d2775", tel, content, "json");
//
//                    call.enqueue(new Callback<String>() {
//                        @Override
//                        public void onResponse(Call<String> call, SucceedResponse<String> response) {
//                            MyLog.i(TAG, response.body().toString());
//                        }
//
//                        @Override
//                        public void onFailure(Call<String> call, Throwable t) {
//
//                        }
//
//                    });

                    Toast.makeText(this, "已发送", Toast.LENGTH_SHORT).show();
                    handler.sendEmptyMessage(CODE_ING); // 重新发送ns秒
                    getCode.setBackgroundResource(R.color.alphaSubColor);
                    getCode.setTextColor(getResources().getColor(R.color.black));
                    getCode.setClickable(false); // 取消点击事件
                }
            }
            break;
            case R.id.commit_Register:
                String resume = resumepasswordEdit.getText().toString();//确认密码
                String password = passwordEdit.getText().toString();
                String city = cityEdit.getText().toString();
                String securityCode = securityCodeEdit.getText().toString();
                tel = telEdit.getText().toString();
                if (tel == null || tel.equals("") || password == null || password.equals("") || resume == null || resume.equals("")
                        || city == null || city.equals("")) {
                    Toast.makeText(this, "请填写完整注册信息", Toast.LENGTH_SHORT).show();
                } else if (password.length() < 6) {
                    Toast.makeText(this, "密码必须大于6位", Toast.LENGTH_SHORT).show();
                    break;
                } else if (!resume.equals(password)) {
                    Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
                } else if (code == ApiService.PHONE_NUM_WRONG || code == ApiService.SMS_SEND_FAILURE) {
                    Toast.makeText(this, "请重新输入手机号进行验证", Toast.LENGTH_SHORT).show();
                } else if (code == ApiService.SMS_SEND_SUCCESS) { // 短信发送成功 1
                    if (securityCode.equals(mobileCode)) {
                        mProgressBar.setVisibility(View.VISIBLE);   // 提交注册信息
                        Retrofit retrofit = new Retrofit.Builder().baseUrl(ApiService.BASE_URL)
                                .addConverterFactory(GsonConverterFactory.create())
                                .build();
                        ApiService apiService = retrofit.create(ApiService.class);
                        Call<RegisterEntry> call = apiService.
                                Register(tel, password, tel, city);//电话号码就是账号 密码 城市
                        call.enqueue(this);
                        // Toast.makeText(this, "提交注册信息", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.Register_case_back:
                finish();
                break;
        }
    }

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_ING:
                    getCode.setText("重新发送(" + tempSecond-- + "s)");
                    if (tempSecond > 0) {
                        handler.sendEmptyMessageDelayed(CODE_ING, 1000); // 重新发送ns秒
                    } else {
                        handler.sendEmptyMessage(CODE_REPEAT); // 重新获取验证码
                    }
                    break;
                case CODE_REPEAT:
                    getCode.setText("重新获取验证码 ");
                    getCode.setBackgroundResource(R.color.subColor);
                    getCode.setTextColor(getResources().getColor(R.color.white));
                    getCode.setClickable(true);
                    tempSecond = 45;
                    break;
                case 100:
                    if (msg.obj.toString() != null && !msg.obj.toString().equals("")) {
                        Gson gson = new Gson();
                        VerifyEntry verifyEntry = gson.fromJson(msg.obj.toString(), VerifyEntry.class);
                        if (verifyEntry.getCode() == 2) { // 短信发送成功
                            LogUtils.i("SendSms:", "SMS_SEND_SUCCESS " + ApiService.SMS_SEND_SUCCESS);
                            code = ApiService.SMS_SEND_SUCCESS;
                        } else if (verifyEntry.getCode() == 403 || verifyEntry.getCode() == 406 || verifyEntry.getCode() == 4030) { // 手机号有误
                            code = ApiService.PHONE_NUM_WRONG;
                        } else {
                            code = ApiService.SMS_SEND_FAILURE;
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }

    @Override
    public void onResponse(Call<RegisterEntry> call, Response<RegisterEntry> response) {
        RegisterEntry body = response.body();
        if (body.getStatus() == 200) {
            mProgressBar.setVisibility(View.GONE);
        }
    }

    @Override
    public void onFailure(Call<RegisterEntry> call, Throwable t) {
        t.printStackTrace();
    }
}

